package com.sls.api.game.servlet;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.sls.api.game.pojo.NutsNetGoodsInfo;
import com.sls.api.game.pojo.NutsNetServerInfo;
import com.sls.api.util.IpUtil;
import com.sls.api.util.NutsNetServerSaxParseXml;
import com.sls.api.util.ResponseDataXmlFormat;
import com.sls.api.util.UtilMD5Encryption;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * @Description:坚果网络商品货源变更
 * @author Wangxuegang
 * @time 2012-09-01
 * 
 */
public class NutsNetGoodsUpdateServlet extends SuperServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger
			.getLogger(NutsNetGoodsUpdateServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setAttribute("org.eclipse.jetty.server.Request.queryEncoding",
				"GBK");
		resp.setContentType("text/html;charset=GBK");
		resp.setStatus(HttpServletResponse.SC_OK);

		// 合作平台编号
		String partnerId = req.getParameter("partnerId");

		// 货源发布序列号
		String serialNumber = req.getParameter("serialNumber");

		// 商品中心商品编号
		String supProductId = req.getParameter("supProductId");

		// 操作类型
		String opCode = req.getParameter("opCode");

		// Sup供货价格单价
		String unitPrice = req.getParameter("unitPrice");

		// 时间戳
		String ts = req.getParameter("ts");

		// 签名字符串
		String sign = req.getParameter("sign");

		// 合作方商户密钥
		NutsNetServerInfo serverInfo = NutsNetServerSaxParseXml.getKeyValue();
		String partnerKey = serverInfo.getPartnerKey().trim();
		boolean flag = checkData(partnerId, serialNumber, supProductId, opCode,
				unitPrice, ts, sign, partnerKey, resp);
		if (flag) { // 数据校验通过
			try {
//				Gson gson = CommonUtil.gson();
				SocketDTO socketChangeVo = createMsg(partnerId, serialNumber,
						supProductId, opCode, unitPrice, ts, sign, req);
				Head head = socketChangeVo.getHead();
				String resCode = head.getResponseCode();
				String resMsg = head.getResponseMessage();
				if (resMsg != null && !("".equals(resMsg))) {
					resMsg = URLDecoder.decode(resMsg, "utf-8"); // 解码
					resMsg = URLEncoder.encode(resMsg, "GBK"); // GBK编码
				}
				

//				String bodyStr = socketChangeVo.getBody();
//				String resBodyStr = gson.fromJson(bodyStr, String.class);

				String xmlStr = ResponseDataXmlFormat.assembleXmlString(
						null, resCode, resMsg);
				resp.getWriter().write(xmlStr);
				resp.getWriter().flush();
				resp.getWriter().close();

			} catch (Exception e) {
				log.error("出错", e);
				ResponseDataXmlFormat.returnResMsg("201", "其他错误", resp);
			}
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		log.info("req" + req);
		try {
			doPost(req, resp);
		} catch (Exception e) {
			log.error("出错", e);
		}
	}

	/**
	 * 数据校验
	 * 
	 * @param partnerId
	 * @param serialNumber
	 * @param supProductId
	 * @param opCode
	 * @param unitPrice
	 * @param ts
	 * @param sign
	 * @param partnerKey
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	private boolean checkData(String partnerId, String serialNumber,
			String supProductId, String opCode, String unitPrice, String ts,
			String sign, String partnerKey, HttpServletResponse resp)
			throws IOException {
		boolean flag = false;

		// 合作平台编号
		if ("".equals(partnerId) || partnerId == null) {
			log.info("合作平台编号为空");
			ResponseDataXmlFormat
					.returnResMsg("101", "缺少必需参数[partnerId]", resp);
		}
		// 货源发布序列号
		else if ("".equals(serialNumber) || serialNumber == null) {
			log.info("货源发布序列号为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[serialNumber]",
					resp);
		}
		// 商品中心商品编号
		else if ("".equals(supProductId) || supProductId == null) {
			log.info("商品中心商品编号为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[supProductId]",
					resp);
		}
		// 操作类型
		else if ("".equals(opCode) || opCode == null) {
			log.info("操作类型为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[opCode]", resp);
		}
		// 时间戳
		else if ("".equals(ts) || ts == null) {
			log.info("时间戳为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[ts]", resp);
		}
		// 签名字符串
		else if ("".equals(sign) || sign == null) {
			log.info("签名字符串为空");
			ResponseDataXmlFormat.returnResMsg("101", "缺少必需参数[sign]", resp);
		} else {
			StringBuilder strbu = new StringBuilder();
			if ("UPDATE".equals(opCode)) { // 更改货源价格
				strbu.append("opCode");
				strbu.append(opCode.trim());
				strbu.append("partnerId");
				strbu.append(partnerId.trim());
				strbu.append("serialNumber");
				strbu.append(serialNumber.trim());
				strbu.append("supProductId");
				strbu.append(supProductId.trim());
				strbu.append("ts");
				strbu.append(ts.trim());
				strbu.append("unitPrice");
				strbu.append(unitPrice.trim());
				strbu.append(partnerKey.trim());

			} else if ("DELETE".equals(opCode)) { // 代表删除货源(下架)
				strbu.append("opCode");
				strbu.append(opCode.trim());
				strbu.append("partnerId");
				strbu.append(partnerId.trim());
				strbu.append("serialNumber");
				strbu.append(serialNumber.trim());
				strbu.append("supProductId");
				strbu.append(supProductId.trim());
				strbu.append("ts");
				strbu.append(ts.trim());
				strbu.append(partnerKey.trim());
			}

			String data = strbu.toString().trim();
			if ("UPDATE".equals(opCode)) { // 更改货源价格
				// Sup供货价格单价
				if ("".equals(unitPrice) || unitPrice == null) {
					log.info("Sup供货价格单价为空");
					ResponseDataXmlFormat.returnResMsg("101",
							"缺少必需参数[unitPrice]", resp);
				}
			}

			boolean checkRes = UtilMD5Encryption.checkMD5Signature(data, sign);
			if (checkRes) {
				flag = true;
			} else {
				log.info("MD5数字签名未通过");
				flag = false;
				ResponseDataXmlFormat.returnResMsg("102", "签名失败", resp);
			}

		}

		return flag;
	}

	/**
	 * 创建Json格式socket消息包
	 * 
	 * @param partnerId
	 * @param supProductId
	 * @param unitPrice
	 * @param name
	 * @param productType
	 * @param parvalue
	 * @param ts
	 * @param sign
	 * @return
	 */
	private SocketDTO createMsg(String partnerId, String serialNumber,
			String supProductId, String opCode, String unitPrice, String ts,
			String sign, HttpServletRequest req) {
		NutsNetGoodsInfo goodsInfo = new NutsNetGoodsInfo();
		goodsInfo.setPartnerId(partnerId);
		goodsInfo.setSerialNumber(serialNumber);
		goodsInfo.setSupProductId(supProductId);
		goodsInfo.setOpCode(opCode);
		goodsInfo.setUnitPrice(unitPrice);
		goodsInfo.setTs(ts);
		goodsInfo.setSign(sign);
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode("020801");
		head.setIp(IpUtil.getIpAddr(req)); // ---------坚果网络IP
		head.setUserId("0"); // ---------坚果网络用户ID
		return super.send(head, goodsInfo);
	}

}
